
<template>
  <!-- 建立考核模板-基础信息 -->
  <div style="display:flex;flex-direction: column; align-items: center;justify-content: center;">
    <!-- 表头步骤条 -->
    <el-card class="ensemble" shadow="always">
      <el-steps :active="actives" style="width:600px" space="330px">
        <el-step title="基础信息"></el-step>
        <el-step title="考核指标"></el-step>
        <el-step title="考核流程设置"></el-step>
      </el-steps>
      <!-- 取消-保存按钮 -->
      <div class="baoCunQuxiao">
        <el-button
          round
          style="width:80px;font-size:16px;font-weight:700;"
          @click.prevent="closeAlert1"
        >取消</el-button>
        <el-button
          @click.prevent="baocunAlert1"
          type="primary"
          v-if="baoCun"
          round
          style="width:80px;font-size:16px;font-weight:700;"
        >保存</el-button>
      </div>
    </el-card>
    <!-- 基础信息表单部分 -->
    <div class="formContent" v-if="page1">
      <el-form label-width="130px" :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="考核表名称" prop="name">
          <el-input
            style="width:500px;margin-left:15px;height: 32px;"
            v-model="ruleForm.name"
            placeholder="请输入考核表名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="考核周期" prop="period">
          <el-radio-group v-model="ruleForm.period">
            <el-radio :label="1" style="margin-left:25px;">月度</el-radio>
            <el-radio :label="2">季度</el-radio>
            <el-radio :label="3">年度</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="考核管理员" prop="assessAdministratorUserId">
          <el-input
            style="width:500px;margin-left:15px;height: 32px;"
            v-model="userNames"
            :disabled="disabledsd"
          ></el-input>
        </el-form-item>
        <el-form-item label="被考核人员" style="position:relative" prop="assessUserType">
          <el-radio-group v-model="ruleForm.assessUserType" @change="changeRadio" fill="#cccccc">
            <el-radio :label="1" :disabled="showSelect1" style="margin-left:25px;">全员</el-radio>
            <el-radio :label="2">指定人</el-radio>
          </el-radio-group>
          <el-row>
            <el-cascader
              v-if="showSelect"
              style="margin-left:15px;"
              :show-all-levels="false"
              placeholder="请选择被考核人员"
              ref="selectUpResId"
              v-model="treeDataValue"
              :options="this.user"
              :props="{ multiple: true,label: 'label',value: 'value', checkStrictly: false }"
              @change="handleNodeClick1"
            ></el-cascader>
          </el-row>
        </el-form-item>
        <el-form-item label="描述" prop="remarks">
          <el-input
            type="textarea"
            v-model="ruleForm.remarks"
            placeholder="请输入模板的描述"
            style="width:500px;margin-left:15px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="nextPage('ruleForm')"
            type="primary"
            round
            style="margin-left:180px;width:113px;height:43px;font-size:18px;border-radius: 50px;"
          >下一步</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- v-on:titleChanged="updateTitle" -->
    <twoStep v-if="page2" @giveFather="updateTitle" @giveFathers="updateTitles" :personInfo="info"></twoStep>
  </div>
</template>
    
    <script>
import {
  addOneStep,
  userOneStep,
  getUserId,
  lookOneMuBan,
  editMuaBan,
  apiPeoLists
} from "@/api2/kaohe"; //新增绩效考核模版表-基础信息数据
import { websock } from "@/websock";
import { returnStatement } from "@babel/types";
import { apiPeoList } from "@/api2/projectManagement/reporting";
import twoStep from "./twoStep.vue";
export default {
  props: ["ids"],
  components: {
    twoStep: twoStep
  },
  data() {
    return {
      idd: this.ids,
      props: { multiple: true },
      disabledsd: true,
      showSelect: false,
      showSelect1: false,
      baoCun: false, //保存按钮
      actives: 1,
      page1: true,
      page2: false,
      disabled: true,
      userNames: "",
      options: [],
      path: [],
      allUser: [],
      user: [],
      peopleList: [],
      value: [],
      departments: [],
      selectTree: [],
      treeDataValue: [],
      cascaderProps: {
        multiple: true,
        checkStrictly: true,
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: "id",
        label: "name",
        leaf: "leaf",
        expandTrigger: "hover"
      },
      defaultProps1: {
        multiple: true,
        children: "children",
        label: "label",
        value: "id",
        emitPath: "true"
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      ruleForm: {
        name: "", //考核表名称
        period: "", //周期
        assessAdministratorUserId: "", //考核管理员
        label: "",
        label1: "",
        assessUserType: "", //被考核人员
        remarks: "", //描述,
        assessorUserId: [],
        treeData: [] // 多选
      },
      //规则校验
      rules: {
        //指标名称校验
        name: [
          { required: true, message: "请输入考核表名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30个字符", trigger: "blur" }
        ],
        period: [{ required: true, message: "周期必选", trigger: "change" }],
        assessUserType: [
          { required: true, message: "被考核人员必选", trigger: "change" }
        ],
        assessAdministratorUserId: [
          { required: true, message: "管理员名称必选", trigger: "change" }
        ]
      }
    };
  },
  async created() {
    this.getUserIds();
    this.getUser();
    this.idd ? this.editONE() : "";
    const res = await apiPeoLists();
    const userList = [];
    for (let i = 0; i !== res.data.deptTreeList.length; i++) {
      userList.push({
        value: i + "",
        label: res.data.deptTreeList[i].name,
        children: [],
      });

      for (let j = 0; j !== res.data.deptTreeList[i].userList.length; j++) {
        userList[i].children.push({
          value: res.data.deptTreeList[i].userList[j].uid,
          label: res.data.deptTreeList[i].userList[j].name
        });
      }
    }
    console.log(userList);
    // 传参： treeData: 树形数据
    console.log(this.user);
    this.user = userList;
  },
  watch: {
    filterText(val) {
      console.log(val);
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    async editONE() {
      console.log(this.idd);
      const id = this.idd;
      const res = await lookOneMuBan(id);
      console.log(res);
      if (res.code == 0) {
        if (res.data.assessUserType == 2) {
          const resd = await apiPeoList();
          this.peopleList = resd.data;
          this.showSelect = true;
          this.disabled = false;
          let arrs = [];
          let arrs1 = [];
          let arr3 = [];
          this.peopleList.forEach(item => {
            res.data.assessorUserId.split(",").forEach(items => {
              if (item.id == items) {
                arrs.push(item.name);
                arrs1.push(item.id);
                arr3.push({ label: item.name, id: item.id });
              }
            });
          });
          this.ruleForm.assessorUserId = arrs1;
          console.log(arr3);
          let arr = [];
          arr3.forEach(elment => {
            let item = this.getTreeIds(this.user, elment.id);
            console.log(item);
            arr.push(item);
          });
          this.treeDataValue = arr;
          console.log(this.treeDataValue);
        } else {
          this.showSelect = false;
          this.disabled = true;
          this.ruleForm.assessorUserId = this.allUser;
        }
        this.ruleForm.name = res.data.name;
        this.ruleForm.period = res.data.period;
        this.ruleForm.assessUserType = Number(res.data.assessUserType);

        // this.ruleForm.assessorUserId = res.data.assessorUserId.split(",");
        this.ruleForm.remarks = res.data.remarks;
        // console.log(res.data.assessorUserId.split(','));
      }
    },
    // 通过子节点ID查找所有关联的父节点
    getTreeIds(tree, nodeId, config) {
      const { children = "children", id = "value" } = config || {};
      const toFlatArray = (tree, parentId) => {
        return tree.reduce((t, _) => {
          const child = _[children];
          return [
            ...t,
            parentId ? { ..._, parentId } : _,
            ...(child && child.length ? toFlatArray(child, _[id]) : [])
          ];
        }, []);
      };
      const getIds = flatArray => {
        let ids = [nodeId];
        // let child = flatArray.find(_ => _[id] === nodeId);
        // console.log(child, ids);
        let child = flatArray.find(_ => _.value == nodeId);
        console.log(child, ids);
        while (child && child.parentId) {
          console.log(ids);
          ids = [child.parentId, ...ids];
          child = flatArray.find(_ => _.value === child.parentId);
        }
        return ids;
      };
      return getIds(toFlatArray(tree));
    },
    //获取用户基本信息
    getUserIds() {
      setTimeout(() => {
        getUserId()
          .then(res => {
            if (res.code == 0) {
              console.log(res);
              this.ruleForm.assessAdministratorUserId = res.data.id;
              this.userNames = res.data.userName;
              console.log(this.ruleForm.assessAdministratorUserId);
            } else {
              console.log(error);
            }
          })
          .catch(e => {
            console.log(e);
          });
      }, 500);
    },
    updateTitle(e) {
      //声明这个函数
      this.actives = Number(e);
      if (e == "3") {
        this.baoCun = true;
      }
    },
    updateTitles(e) {
      //声明这个函数
      this.idd = e;
      this.page1 = true;
      this.page2 = false;
    },
    // 获取所有人员id
    async getUser() {
      const res = await userOneStep();

      // this.user = res.data.deptTreeList;
      let arr = res.data.deptTreeList;
      console.log(this.user);
      let users = [];
      res.data.userList.forEach(item => {
        users.push(item.id);
      });
      res.data.deptTreeList.forEach(item => {
        this.getTreePath(item.children, this.path, arr);
      });
      this.allUser = users;
      // this.peopleList = res.data.userList;
    },
    getTreePath(val, pushd, arr) {
      console.log(val, pushd, arr);
      // this.user = arr;
      val.forEach(item => {
        if (item.children) {
          pushd.push({ id: item.id, name: item.label });
          item.children.forEach(data => {
            if (data.children) {
              pushd.push({ id: data.id, name: data.label });
              this.getTreePath(data.children, pushd);
            } else {
              return;
            }
          });
        } else {
          return;
        }
      });
      console.log(pushd);
      this.departments = pushd;
    },
    // 填写数量 radio单选事件changeRadio
    changeRadio(val) {
      if (val == 2) {
        this.disabled = false;
        this.showSelect = true;
      } else {
        this.disabled = true;
        this.showSelect = false;
      }
    },
    handleChange(val) {
      console.log(val);
      console.log(this.user);
      this.ruleForm.assessAdministratorUserId = this.$refs[
        "selectUpResId"
      ].getCheckedNodes()[0].data.id;
      console.log(this.$refs["selectUpResId"].getCheckedNodes()[0].label);
      console.log(this.$refs["selectUpResId"].getCheckedNodes()[0].data.id);
      this.$refs.selectUpResId.blur();
    },

    handleNodeClick1(data) {
      const result = [];
      for (let j = 0; j < data.length; j++) {
        result.push(data[j][data[j].length - 1]);
      }
      this.ruleForm.assessorUserId = Array.from(new Set(result));
    },
    handleClear1() {
      // 将选择器的值置空
      this.ruleForm.assessorUserId = "";
      this.ruleForm.treeData = "";
    },
    handleClear() {
      // 将选择器的值置空
      this.ruleForm.label = "";
      this.ruleForm.assessAdministratorUserId = "";
    },
    baocunAlert1(e) {
      this.$emit("fatherMethod");
      this.$message({
        message: "保存成功",
        type: "success"
      });
    },
    closeAlert1(e) {
      this.$confirm("确定退出吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$emit("fatherMethod");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    nextPage(formName) {
      if (!this.idd) {
        let arr = [];
        if (
          this.ruleForm.assessorUserId.length == 0 &&
          this.disabled == false
        ) {
          this.$message.error("指定人至少选一个!");
          return;
        } else {
          this.ruleForm.assessorUserId.map(item => {
            arr.push(item);
          });
        }
        let uniqueArray = Array.from(new Set(arr)).toString();
        let allUniqueArray = Array.from(new Set(this.allUser)).toString();
        console.log(uniqueArray);
        const jxAssessTemplate = {
          assessAdministratorUserId: this.ruleForm.assessAdministratorUserId,
          assessUserType: this.ruleForm.assessUserType,
          name: this.ruleForm.name,
          period: this.ruleForm.period,
          remarks: this.ruleForm.remarks,
          assessorUserId:
            this.ruleForm.assessUserType == 1 ? allUniqueArray : uniqueArray
        };
        console.log(jxAssessTemplate);
        this.$refs[formName].validate(valid => {
          if (valid) {
            // 调用接口
            addOneStep(jxAssessTemplate)
              .then(res => {
                console.log(res);
                if (res.code == 0) {
                  this.info = res.data.id; //父组件中相关的值赋值给info
                  this.$message({
                    message: "模板添加成功",
                    type: "success"
                  });
                  this.actives = 2;
                  this.page1 = false;
                  this.page2 = true;
                } else {
                  return false;
                }
              })
              .catch(e => {
                console.log(e);
              });
          }
        });
      } else {
        let arr = [];
        if (
          this.ruleForm.assessorUserId.length == 0 &&
          this.disabled == false
        ) {
          this.$message.error("指定人至少选一个!");
          return;
        } else {
          this.ruleForm.assessorUserId.map(item => {
            arr.push(item);
          });
        }
        let uniqueArray = Array.from(new Set(arr)).toString();
        let allUniqueArray = Array.from(new Set(this.allUser)).toString();
        console.log(uniqueArray);
        const jxAssessTemplate = {
          id: this.idd,
          assessAdministratorUserId: this.ruleForm.assessAdministratorUserId,
          assessUserType: this.ruleForm.assessUserType,
          name: this.ruleForm.name,
          period: this.ruleForm.period,
          remarks: this.ruleForm.remarks,
          assessorUserId:
            this.ruleForm.assessUserType == 1 ? allUniqueArray : uniqueArray
        };
        console.log(jxAssessTemplate);
        this.$refs[formName].validate(valid => {
          if (valid) {
            // 调用接口
            editMuaBan(jxAssessTemplate)
              .then(res => {
                console.log(res);
                if (res.code == 0) {
                  this.info = res.data.id; //父组件中相关的值赋值给info
                  this.$message({
                    message: "模板编辑成功",
                    type: "success"
                  });
                  this.actives = 2;
                  this.page1 = false;
                  this.page2 = true;
                } else {
                  return false;
                }
              })
              .catch(e => {
                console.log(e);
              });
          }
        });
      }
    }
  }
};
</script>
    
    <style lang="scss" scoped>
.ensemble {
  // position: relative;
  text-align: center;
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: center;
  height: 100px;
  width: 100%;
  .baoCunQuxiao {
    position: absolute;
    width: 180px;
    top: 28px;
    right: 70px;
  }
}

.formContent {
  margin-top: 55px;
}
::v-deep .el-form-item__content {
  line-height: 74px;
}
::v-deep .el-form-item__label {
  font-size: 16px;
  line-height: 74px;
}
// ::v-deep .el-input__inner {
//   background-color: #dcdfe6;
//   border: none;
// }

::v-deep [data-v-125ad6e6] .el-step__title.is-wait {
  color: #000;
}
::v-deep .el-radio__label {
  color: #606266;
  font-weight: 700;
  line-height: 0px;
  margin-right: 30px;
  font-size: 16px;
}
::v-deep .el-radio__inner {
  width: 16px;
  height: 16px;
}
::v-deep .el-radio__input {
  vertical-align: sub;
}

// ::v-deep .el-textarea__inner {
//   background-color: #dcdfe6;
//   border: none;
// }
::v-deep .el-step__title.is-wait {
  font-weight: 700;
  color: #ccc;
}
::v-deep .el-step__head.is-wait {
  color: #ccc;
  border-color: #ccc;
}
::v-deep .el-step.is-horizontal .el-step__line {
  height: 0px;
  top: 0px;
}
::v-deep .el-step.is-horizontal,
.el-step__icon-inner {
  display: flex;
  justify-items: left;
  font-size: 16px;
}
::v-deep .el-step__icon-inner {
  font-size: 16px;
}
::v-deep .el-step__head {
  width: 23%;
  // margin-left: 130px;
}
::v-deep .el-step__title {
  line-height: 30px;
  font-weight: 700;
  font-size: 18px;
}
::v-deep .el-step__icon {
  width: 31px;
  height: 30px;
}
::v-deep .el-step__head.is-finish {
  border: #0a73e1;
}
::v-deep .el-tree-node {
  .is-leaf + .el-checkbox .el-checkbox__inner {
    display: inline-block;
  }
  .el-checkbox .el-checkbox__inner {
    display: none;
  }
}
::v-deep .el-cascader-panel li[aria-haspopup] .el-checkbox {
  display: none;
}
</style>